package it.uniroma2.art.coda.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;

import javax.imageio.stream.FileImageInputStream;

import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.cas.FSIndexRepository;
import org.apache.uima.cas.FSIterator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.FSIndexRepositoryImpl;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.pear.tools.PackageBrowser;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceManager;
import org.apache.uima.resource.ResourceSpecifier;
import org.apache.uima.util.InvalidXMLException;
import org.apache.uima.util.XMLInputSource;

import it.uniroma2.art.coda.core.CODACore;
import it.uniroma2.art.coda.projectionrule.ProjectionRulesModel;

public class SampleCode {

	//private static private AnalysisEngine ae = null;
	
	private static CODACore codaCore = null;
	
	//private static String aeSimpleNamePath = "C:/Users/Andrea/AppData/Roaming/Mozilla/Firefox/Profiles/ks569oks.default/SemanticTurkeyData/uimast/pears/SimpleName";
	//private static String aeEmailPath = "C:/Users/Andrea/AppData/Roaming/Mozilla/Firefox/Profiles/ks569oks.default/SemanticTurkeyData/uimast/pears/EmailRecognizer";
	
	//private static String aggregateAEPath = "E:/UIMATest";
	private static String aggregateAEFilePath = "E:/CODATest/provaAggregateAE.xml";
	//private static String aeSimpleNamePath = "E:/UIMATest/SimpleName";
	//private static String aeEmailPath = "E:/UIMATest/EmailRecognizer";
	
	
	private static String txtFilePath = "E:/CODATest/test.txt";
	
	private static String dirComponentsPath = "E:/CODATest/components";
	
	private static String textToBeAnnotatate;
	
	private static Collection <JCas> jcasCollection = new ArrayList<JCas>();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		try {
			
			//read the input file containig the test to be analized
			FileReader fir = new FileReader(txtFilePath);
			BufferedReader  br = new BufferedReader (fir); 
			
			//TODO vedere bene il discorso dell'encoding
			
			StringBuilder contents = new StringBuilder();
			String line;
			
			while (( line = br.readLine()) != null){
	          contents.append(line);
	          contents.append(System.getProperty("line.separator"));
	        }
			textToBeAnnotatate = contents.toString();

			
			//TODO use AE to analyze a txt (try using two AE, such as SimpleName e 
			//EmailRecognizer one after the other)
			
			//URI pearDir;
			XMLInputSource in;
			//PackageBrowser browser;
			ResourceSpecifier specifier;
			//ResourceManager resManager;
			AnalysisEngine ae;
			JCas annotCas;
			//JCas annotCas2;
			
			/*// first the Simple Name
			pearDir = new File(aeSimpleNamePath).toURI();
			browser = new PackageBrowser(new File(pearDir.getPath()));
			in = new XMLInputSource(browser.getInstallationDescriptor().getMainComponentDesc());
			specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
			resManager = UIMAFramework.newDefaultResourceManager();
			resManager.setExtensionClassPath(browser.buildComponentClassPath(), true);
			ae = UIMAFramework.produceAnalysisEngine(specifier, resManager, null);
			ae.setConfigParameterValue("Encoding", "UTF-8");
			annotCas =ae.newJCas();
			//annotCas.setDocumentText(tagCas.getView("plainTextDocument").getDocumentText());
			annotCas.setDocumentText(textToBeAnnotatate);
			annotCas.setDocumentLanguage("it");
			ae.process(annotCas);
			jcasCollection.add(annotCas);
			
			//TODO now invoke the Email recognizer AR
			pearDir = new File(aeEmailPath).toURI();
			browser = new PackageBrowser(new File(pearDir.getPath()));
			in = new XMLInputSource(browser.getInstallationDescriptor().getMainComponentDesc());
			specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
			resManager = UIMAFramework.newDefaultResourceManager();
			resManager.setExtensionClassPath(browser.buildComponentClassPath(), true);
			ae = UIMAFramework.produceAnalysisEngine(specifier, resManager, null);
			ae.setConfigParameterValue("Encoding", "UTF-8");
			annotCas2 = ae.newJCas();
			annotCas2.setDocumentText(textToBeAnnotatate);
			annotCas2.setDocumentLanguage("it");
			ae.process(annotCas2);
			jcasCollection.add(annotCas2);
			*/
			
			//pearDir = new File(aggregateAEPath).toURI();
			//browser = new PackageBrowser(new File(pearDir.getPath()));
			//in = new XMLInputSource(browser.getInstallationDescriptor().getMainComponentDesc());
			in = new XMLInputSource(aggregateAEFilePath);
			specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
			//resManager = UIMAFramework.newDefaultResourceManager();
			//resManager.setExtensionClassPath(browser.buildComponentClassPath(), true);
			//resManager.setExtensionClassPath(aeSimpleNamePath+"/bin",true); // TODO forse non serve
			//resManager.setExtensionClassPath(aeEmailPath+"/bin",true); // TODO forse non serve
			//ae = UIMAFramework.produceAnalysisEngine(specifier, resManager, null);
			ae = UIMAFramework.produceAnalysisEngine(specifier);
			ae.setConfigParameterValue("Encoding", "UTF-8");
			annotCas = ae.newJCas();
			//annotCas.setDocumentText(tagCas.getView("plainTextDocument").getDocumentText());
			annotCas.setDocumentText(textToBeAnnotatate);
			//annotCas.setDocumentLanguage("it");
			ae.process(annotCas);
			
			
			//ae.
			//jcasCollection.add(annotCas);
			FSIndex indexAnnotations = annotCas.getAnnotationIndex();
			Iterator<Annotation> annoIt = indexAnnotations.iterator();
			Annotation ann = annoIt.next();
			System.out.println("testo analizzato: "+ann.getCoveredText());
			while(annoIt.hasNext()){
				Annotation annotation = annoIt.next();
				String text = annotation.getCoveredText();
				int begin = annotation.getBegin();
				int end = annotation.getEnd();
				String type = annotation.getType().getName();
				System.out.println("text: "+text+"\tbegin: "+begin+"\tend:"+end+"\ttype: "+type); 
			}
			System.out.println("FINE stampa annotazioni");	
			/*
			System.out.println("fine prima stampa");
			FSIterator 	fsIter = annotCas.getAnnotationIndex().iterator();
			while(fsIter.isValid()){
				FeatureStructure fs = fsIter.get();
				System.out.println(((AnnotationFS)fs).getCoveredText());
				
				fsIter.moveToNext();
			}*/
			
			//TODO print all the annotation to better understand how the JCAS works
			/*Iterator<JCas> iterJCas = jcasCollection.iterator();
			while(iterJCas.hasNext()){
				JCas jcas = iterJCas.next();
				FSIndex indexAnnotations = jcas.getAnnotationIndex();
				System.out.println()
				//FSIndex indexAnnotations = annotCas2.getAnnotationIndex();
				Iterator<Annotation> annoIt = indexAnnotations.iterator();
				Annotation ann = annoIt.next();
				while(annoIt.hasNext()){
					Annotation annotation = annoIt.next();
					String text = annotation.getCoveredText();
					int begin = annotation.getBegin();
					int end = annotation.getEnd();
					String type = annotation.getType().getName();
					System.out.println("text: "+text+"\tbegin: "+begin+"\tend:"+end+"\ttype:"+type); 
				}
			}*/
		
			
			/*
			Iterator iterView = annotCas.getViewIterator();
			while(iterView.hasNext()){
				System.out.println(iterView.next().toString());
			}
			
			System.out.println("FINE iterator view");
			
			
			FSIndexRepository fsIndex = annotCas.getFSIndexRepository();
			Iterator<FSIndex> iterFS = fsIndex.getIndexes();
			while(iterFS.hasNext()){
				FSIndex fs = iterFS.next();
				System.out.println(fs.getType()+"\t"+fs.toString());
			}
			*/
			
			
			
			//prova lettura file XML PR
			String XMLPRPath = "E:/CODATest/provaPR.xml";
			System.out.println("inizio lettura file "+XMLPRPath); 
			ProjectionRulesModel prModel = new ProjectionRulesModel();
			//XMLParserPR xmlParserPR = new XMLParserPR();
			//xmlParserPR.initialize(prModel, XMLPRPath);
			//xmlParserPR.startParsingPR();
			prModel.printModel();
			System.out.println("dopo stampa modello PR"); 
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidXMLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceInitializationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AnalysisEngineProcessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
